<?php

namespace Biz\service\theParagraph;


use Biz\cache\theparagraph\Goods as cTGoods;
use Biz\service\Goods as sGoods;
use Doraemon\tools\Log;
use Biz\service\SearchGoods;
use Biz\service\esSearch\Goods as esGoods;
/**
 * @deprecated
 */
class Goods
{

    const SHOP_IDS = [
        4372030,
//        164608,//测试后删除
//        63481,//测试后删除
//        1962205,//好好测，测试后删除
    ]; //节选店铺id
    const INDEX_TAG_LIST = [
        'CK','SJ','MD'
//        '尖货推荐','必买清单',//测试后删除
    ];
    const INDEX_B_TAG_LIST = [
        'theParagraph节选',
//        '黄铜',//测试后删除
    ];
    const MAX_COUNT = 50; //瀑布流最多显示50个商品
    const RECOMMEND_MAX_COUNT = 20; //瀑布流最多显示50个商品

    /**
     * @desc 规则
     * A类：商家id=4372030 商品标签含有CK/SJ/MD
     * B类：其他商家，商品标签含有「theParagraph节选」
     * 瀑布流最多显示50个商品
     * A、B混合展示
     * 商品出现顺序随机，每次刷新页面顺序随机重排
     * @param int $uid 用户id
     * @param int $page 页码
     * @return array
     */
    public static function indexList($uid = 0, $page = 1)
    {
        $list = [];
        $has_next = false;
        try {
            $pageSize = 20;
            $fresh = $page == 1 && $uid > 0;
            $totalGoodsIds = self::getCachePool($uid, $fresh);
            $limit = ($page - 1) * $pageSize;
            $has_next = ($page * $pageSize) < count($totalGoodsIds);
            if (!is_array($totalGoodsIds)) {
                throw new \Exception('错误数据,data:' . json_encode($totalGoodsIds));
            }
            $totalGoodsIds = array_slice($totalGoodsIds, $limit, $pageSize);
            $list = array_values(sGoods::Goods($totalGoodsIds));
        } catch (\Exception $e) {
            $trace = [
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'message' => $e->getMessage(),
            ];
            Log::error('瀑布流error', compact('uid','totalGoodsIds', 'trace'));
        }
        return compact('list', 'has_next');
    }

    /**
     * @desc 获取商品池缓存
     * @param int $uid
     * @param bool $fresh
     * @return array
     */
    public static function getCachePool($uid = 0, $fresh = false)
    {
        if (!$fresh && cTGoods::keyExists($uid)) {
            $response = cTGoods::getData($uid);
            $response = empty($response) ?  self::getGoodsPool() : [];
        } else {
            $response = self::getGoodsPool();
            if (is_array($response) && !empty($response)) {
                cTGoods::setData($uid, $response);
            }
        }
        return $response;
    }

    /**
     * @desc 获取商品池
     * @return array
     */
    private static function getGoodsPool()
    {
        $totalGoodsIds = [];
        $aGoodsIds = SearchGoods::searchEntrance(
            ['shop_id' => self::SHOP_IDS, 'tags_content' => self::INDEX_TAG_LIST, 'source' => esGoods::SOURCE_THE_PARAGRAPH],
            esGoods::SCENES_THE_PARAGRAPH_INDEX_LIST,0, 1, '*'
        );

        $totalGoodsIds = array_merge($totalGoodsIds, $aGoodsIds['rows']);

        $bGoodsIds = SearchGoods::searchEntrance(
            ['tags_content' => self::INDEX_TAG_LIST, 'source' => esGoods::SOURCE_THE_PARAGRAPH],
            esGoods::SCENES_THE_PARAGRAPH_INDEX_LIST,0, 1, '*'
        );

        $totalGoodsIds = array_merge($totalGoodsIds, $bGoodsIds['rows']);

        $totalGoodsIds = array_unique($totalGoodsIds);
        shuffle($totalGoodsIds);
        return array_slice($totalGoodsIds, 0, self::MAX_COUNT);
    }

    /**
     * @desc 根据搜索条件获取商品池
     * @param $condition array solr搜索条件
     * @param int $length 分页长度
     * @param bool $single 查询一次
     * @return array
     */
    private static function getGoodsPoolByCondition($condition, $length = 100, $single = false)
    {
        $totalPage = 1;
        $totalGoodsIds = [];
        for ($i = 1; $i <= $totalPage; $i ++) {
            try {
                $rs = \Biz\service\search\Goods::searchTheparagraphGoodsByCondition($condition, $i, $length);
                $total = isset($rs['total']) ? $rs['total'] : 0;
                $list = isset($rs['rows']) ? $rs['rows'] : [];
                $listGoodsIds = array_column($list, 'id');
                if ($single) return $listGoodsIds;
                $totalGoodsIds = array_merge($totalGoodsIds, $listGoodsIds);
                $totalPage = ceil($total / $length);
            } catch (\Exception $e) {
                $trace = [
                    'file' => $e->getFile(),
                    'line' => $e->getLine(),
                    'message' => $e->getMessage(),
                ];
                Log::info('solr request', compact('trace'));
            }
        }
        return $totalGoodsIds;
    }

    /**
     * @desc 商品详情更多商品推荐
     * 推荐商品 与当前商品 属于同二级类目
     * A商家id=4372030
     * B屏蔽指定其他商家
     * C小程序抓取的商城部分商品，类目=家具（1级）、灯具（2级
     * A60%>B10%>C30%  12 2 6
     * @param $goodsId
     * @return array
     */
    public static function recommendByCate($goodsId)
    {
        $maxCount = self::RECOMMEND_MAX_COUNT;
        $goodsInfo = sGoods::Goods($goodsId);
        $second_cate_id = isset($goodsInfo['second_category_id']) ? $goodsInfo['second_category_id'] : 0;
        $diff = 0;
        $partACount = 10;
        $partBCount = 10;

        $aRs = SearchGoods::searchEntrance(
            ['shop_id' => self::SHOP_IDS,
             'second_category_id' => $second_cate_id,
             'id[!]' => $goodsId,
             'source' => esGoods::SOURCE_THE_PARAGRAPH
            ],
            esGoods::SCENES_THE_PARAGRAPH_GOODS_RECOMMEND_A,0, 1, $maxCount
        );

        $partA = array_slice($aRs['rows'], 0, $partACount);
        $diff += $partACount - count($partA);

        $bRs = SearchGoods::searchEntrance(
            ['second_category_id' => $second_cate_id,
             'tags_content' => self::INDEX_TAG_LIST,
             'id[!]' => $goodsId,
             'source' => esGoods::SOURCE_THE_PARAGRAPH
            ],
            esGoods::SCENES_THE_PARAGRAPH_GOODS_RECOMMEND_B,0, 1, $maxCount
        );

        $partB = array_slice($bRs['rows'], 0, $partBCount);

        $goodsIds = array_merge($partA, $partB);

        $goodsIds = array_unique($goodsIds);
        $goodsIds = array_slice($goodsIds, 0, $maxCount);

        return array_values(sGoods::Goods($goodsIds));
    }


}
